package com.tnr.scgcxx.service.safty.impl;

import java.util.ArrayList;
import java.util.List;

import com.tnr.scgcxx.dto.safty.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tnr.scgcxx.dao.safty.HomeDao;
import com.tnr.scgcxx.dto.MenuDto;
import com.tnr.scgcxx.model.safty.Module;
import com.tnr.scgcxx.service.safty.HomeService;

@Service
public class HomeServiceImpl implements HomeService {
	
	@Autowired
	private HomeDao homeDao;

	@Override
	public List<MenuDto> getMenus() {
		List<Module> moduleList = homeDao.findMenus();

		List<MenuDto> mainMenuList = new ArrayList<MenuDto>();
		MenuDto currMainMenu=null;
		for(Module m : moduleList) {
			if(m.getM_pid()==null) {
				currMainMenu=new MenuDto();
				currMainMenu.setMenuId(m.getM_id());
				currMainMenu.setMenuName(m.getM_name());
				currMainMenu.setSubMenuList(new ArrayList<MenuDto>());
				mainMenuList.add(currMainMenu);
			}else {
				MenuDto subMenu=new MenuDto();
				subMenu.setMenuId(m.getM_id());
				subMenu.setMenuName(m.getM_name());
				subMenu.setMenuUrl(m.getM_url());

				currMainMenu.getSubMenuList().add(subMenu);
			}
		}

		return mainMenuList;
	}

	@Override
	public List<MenuDto> getMenusByUId(String u_id) {
		List<Module> menusByUId = homeDao.findMenusByUId(u_id);
		List<MenuDto> menuDtoList = new ArrayList<MenuDto>();
		MenuDto menuDto=null;
		for (Module m :menusByUId) {
			if (menuDto==null || !menuDto.getMenuId().equals(m.getP_id())){
				menuDto = new MenuDto();
				menuDto.setMenuId(m.getP_id());
				menuDto.setMenuName(m.getP_name());
				menuDto.setSubMenuList(new ArrayList<MenuDto>());
				menuDtoList.add(menuDto);
			}
			MenuDto subMenu = new MenuDto();
			subMenu.setMenuId(m.getM_id());
			subMenu.setMenuName(m.getM_name());
			subMenu.setMenuUrl(m.getM_url());
			menuDto.getSubMenuList().add(subMenu);
		}
		return menuDtoList;
	}

	@Override
	public List<Module> getMobileMenus(UserDto userDto) {
		return homeDao.findMobileMenus(userDto);
	}


}
